#include <vector>
#include <queue>

using namespace std;
struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
  right(right) {}
 };


class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> ret;
        if(root == nullptr)
            return ret;

        vector<vector<int>> vv;
        queue<TreeNode*> q; 
        q.push(root);
        while(!q.empty())
        {
            int size = q.size();
            vector<int> tmp;
            for(int i=0;i<size;i++)
            {
                TreeNode* node = q.front();
                q.pop();
                tmp.push_back(node->val);
                if(node->left)
                    q.push(node->left);
                if(node->right)
                    q.push(node->right);
            }

            vv.push_back(tmp);
        }

        for(auto e:vv)
        {
            ret.push_back(e[e.size()-1]);
        }

        return ret;
    }
};